<template>
  <div class="easyDisplay">
    <!--  表格顶部  -->
    <div class="header">
      <div class="operation" v-if="operations">
        <div class="operationItem" v-for="(operation,index) in operations" :key="index">
          <el-button v-if="operation == 'add'" type="primary" plain size="small" @click="clickAdd">新增</el-button>
          <el-button v-else-if="operation == 'batch_delete'" type="danger" plain size="small" @click="clickBatchDelete">批量删除</el-button>
          <slot v-else :name="operation" :tableData="{data: data, selectedRows: selectedRows}">
            {{operation}}
          </slot>
        </div>
      </div>
      <div class="query">
        <el-form :model="queryForm" :inline="true" size="mini">
          <el-form-item v-if="field.is_query" :label="field.label" v-for="field in metadata" :key="field.id">
            <el-input v-if="field.field_type == 'string'" v-model="queryForm[field.field]" :placeholder="`请输入${field.label}`"></el-input>
            <el-input-number v-if="field.field_type == 'int'" v-model="queryForm[field.field]" :min="0" :max="150" :label="field.label"></el-input-number>
            <el-input-number v-if="field.field_type == 'float'" v-model="queryForm[field.field]" :min="0" :max="150" :label="field.label" :precision="2"></el-input-number>
            <el-select v-if="field.field_type == 'select'" v-model="queryForm[field.field]" :placeholder="`请选择${field.label}`">
              <el-option v-for="(option,option_index) in field.dict" :label="option.label" :value="option.value" :key="option_index"></el-option>
            </el-select>
            <el-date-picker v-if="field.field_type == 'date'" type="daterange" :placeholder="`请选择${field.label}`" v-model="queryForm[field.field]" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            <el-date-picker v-if="field.field_type == 'datetime'" type="datetimerange" :placeholder="`请选择${field.label}`" v-model="queryForm[field.field]" format="yyyy 年 MM 月 dd 日  HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="pagination.pageNum = 1;getData()">查询</el-button>
            <el-button @click="queryForm = {};getData()">清空</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-divider></el-divider>
    <!--  表格部分  -->
    <div class="table">
      <el-table stripe :data="data" @selection-change="handleSelectionChange" max-height="450">
        <el-table-column type="selection"></el-table-column>
        <template v-for="field in metadata">
          <el-table-column v-if="field.display && field.field_type === 'date'" sortable :prop="field.field" :label="field.label" :formatter="dateFormatter" :key="field.id"></el-table-column>
          <el-table-column v-else-if="field.display && field.field_type === 'datetime'" sortable :prop="field.field" :label="field.label" :formatter="datetimeFormatter" :key="field.id"></el-table-column>
          <el-table-column v-else-if="field.display && field.field_type === 'select'" :prop="field.field" :label="field.label" :formatter="dictFormatter" :key="field.id"></el-table-column>
          <el-table-column v-else-if="field.display" :prop="field.field" :label="field.label" :key="field.id"></el-table-column>
        </template>
        <el-table-column
            fixed="right"
            label="操作">
          <template slot-scope="scope">
            <slot name="row-action" :row="scope.row">
              <!-- 默认内容：如果父组件不传插槽，则显示默认的“编辑”按钮 -->
              <el-button type="text" @click="clickEdit(scope.row)" size="small">
                编辑
              </el-button>
            </slot>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--  分页组件  -->
    <div class="footer">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.pageNum"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
      </el-pagination>
    </div>
    <!--  默认新增窗口  -->
    <el-dialog title="新增" :visible.sync="addDialogVisible" width="30%">
      <div class="add_dialog_body">
        <el-form ref="addForm" :model="addForm" size="mini" label-width="80px" :rules="rules">
          <el-form-item v-if="field.is_add" :prop="field.field" :label="field.label" v-for="field in metadata">
            <el-input v-if="field.field_type == 'string'" v-model="addForm[field.field]" :placeholder="`请输入${field.label}`" style="width: 50%;"></el-input>
            <el-input-number v-if="field.field_type == 'int'" v-model="addForm[field.field]" :min="0" :max="150" :label="field.label"></el-input-number>
            <el-input-number v-if="field.field_type == 'float'" v-model="addForm[field.field]" :min="0" :max="150" :label="field.label" :precision="2"></el-input-number>
            <el-select v-if="field.field_type == 'select'" v-model="addForm[field.field]" :placeholder="`请选择${field.label}`">
              <el-option v-for="option in field.dict" :label="option.label" :value="option.value"></el-option>
            </el-select>
            <el-date-picker v-if="field.field_type == 'date'" type="date" :placeholder="`请选择${field.label}`" v-model="addForm[field.field]" style="width: 70%" format="yyyy 年 MM 月 dd 日"></el-date-picker>
            <el-date-picker v-if="field.field_type == 'datetime'" type="datetime" :placeholder="`请选择${field.label}`" v-model="addForm[field.field]" style="width: 70%" format="yyyy 年 MM 月 dd 日  HH:mm:ss"></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="saveAdd">保 存</el-button>
      </div>
    </el-dialog>
    <!--  默认编辑窗口  -->
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="30%">
      <div class="edit_dialog_body">
        <el-form ref="editForm" :model="editForm" size="mini" label-width="80px" :rules="rules">
          <el-form-item v-if="field.is_update" :prop="field.field" :label="field.label" v-for="field in metadata">
            <el-input v-if="field.field_type == 'string'" v-model="editForm[field.field]" :placeholder="`请输入${field.label}`" style="width: 50%;"></el-input>
            <el-input-number v-if="field.field_type == 'int'" v-model="editForm[field.field]" :min="0" :max="150" :label="field.label"></el-input-number>
            <el-input-number v-if="field.field_type == 'float'" v-model="editForm[field.field]" :min="0" :max="150" :label="field.label" :precision="2"></el-input-number>
            <el-select v-if="field.field_type == 'select'" v-model="editForm[field.field]" :placeholder="`请选择${field.label}`">
              <el-option v-for="option in field.dict" :label="option.label" :value="option.value"></el-option>
            </el-select>
            <el-date-picker v-if="field.field_type == 'date'" type="date" :placeholder="`请选择${field.label}`" v-model="editForm[field.field]" style="width: 70%" format="yyyy 年 MM 月 dd 日"></el-date-picker>
            <el-date-picker v-if="field.field_type == 'datetime'" type="datetime" :placeholder="`请选择${field.label}`" v-model="editForm[field.field]" style="width: 70%" format="yyyy 年 MM 月 dd 日  HH:mm:ss"></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="warning" @click="resetForm('editForm')">重 置</el-button>
        <el-button type="primary" @click="saveEdit">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="js">
import request from '@/utils/request'

export default {
  name: 'easy-display',
  components: {
  },
  props: {
    tableName: String,
    operations:{
      type: Array,
      default: ()=>[]
    },
  },
  data () {
    return {
      metadata: [],
      data: [],
      queryForm: {},
      addForm: {},
      editForm: {},
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      addDialogVisible: false,
      editDialogVisible: false,
      selectedRows: [],
      rules: {},
    }
  },
  mounted() {
    let self = this
    //根据表名获取元数据信息
    request.get(`/easyDisplay/metadata/${self.tableName}`)
        .then(data => {
          self.metadata = data
          //根据元数据组装rules
          let rules = {};
          self.metadata.forEach(item => {
            if (item.rule && Array.isArray(item.rule)) {
              rules[item.field] = JSON.parse(JSON.stringify(item.rule));
            }
          });
          self.rules = rules;
          //读取数据
          self.getData()
        })
        .catch(error => {
          console.error('获取元数据失败:', error)
        })

  },
  computed: {},
  methods: {
    dateFormatter(row, column) {
      let dateFormated = new Date(row[column.property]).toLocaleString('zh-CN', {
        year: 'numeric', month: '2-digit', day: '2-digit',
      }).replace(/\//g, '-');
      return dateFormated
    },
    datetimeFormatter(row, column) {
      let dateFormated = new Date(row[column.property]).toLocaleString('zh-CN', {
        year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit', minute: '2-digit', second: '2-digit',
        hour12: false
      }).replace(/\//g, '-');
      return dateFormated
    },
    dictFormatter(row, column) {
      console.log('dictFormatter',row, column)
      let field = this.metadata.filter(item => item.field_type === 'select')
          .find(item => item.field === column.property)
      if (field && field.dict) {
        return field.dict.find(item => item.value === row[column.property]).label
      }
      return row[column.property]
    },
    handleSizeChange(pageSize) {
      this.pagination.pageSize = pageSize
      this.getData()
    },
    handleCurrentChange(pageNum) {
      this.pagination.pageNum = pageNum
      this.getData()
    },
    getData() {
      let self = this
      //获取数据
      request.post('/easyDisplay/getData', {
        tableName: self.tableName,
        query: self.queryForm,
        page: self.pagination
      }, {
        headers: { 'Content-Type': 'application/json' }
      }).then(data => {
        self.data = data.list
        self.pagination.total = data.total
      }).catch(error => {
        console.error('获取数据失败:', error)
      })
    },
    clickBatchDelete() {
      let self = this
      if (!self.selectedRows || (self.selectedRows.length === 0)) {
        self.$message.warning('请选择要删除的行')
      }else {
        self.$confirm('此操作将永久删除选中的数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //todo 调用接口删除
          request.post('/easyDisplay/deleteByIds', {
            tableName: self.tableName,
            ids: self.selectedRows.map(item => item.id),
          }, {
            headers: { 'Content-Type': 'application/json' }
          }).then(data => {
            console.log('删除成功:', data)
            //更新数据
            self.pagination.pageNum = 1
            self.getData()
          }).catch(error => {
            console.error('获取数据失败:', error)
          })
          self.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          self.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    },
    clickAdd() {
      this.addDialogVisible = true
    },
    cancelAdd() {
      this.addDialogVisible = false
      this.resetForm('addForm')
    },
    saveAdd() {
      let self = this
      self.$refs["addForm"].validate((valid) => {
        if (valid) {
          //todo 调用接口存储
          request.post('/easyDisplay/saveData', {
            tableName: self.tableName,
            data: self.addForm,
          }, {
            headers: { 'Content-Type': 'application/json' }
          }).then(data => {
            self.$message.success('添加成功!');
            self.addDialogVisible = false
            //重置表单数据
            self.resetForm('addForm')
            //刷新数据
            self.getData()
          }).catch(error => {
            console.error('新增数据失败:', error)
          })
        } else {
          return false;
        }
      });
    },
    clickEdit(row) {
      let self = this
      let copyEditRow = JSON.parse(JSON.stringify(row))
      //对row中的时间类型做处理
      self.metadata.filter(field => field.field_type === 'date' || field.field_type === 'datetime').forEach(field => {
        copyEditRow[field.field] = new Date(copyEditRow[field.field])
      })
      this.editForm = copyEditRow
      this.editDialogVisible = true
      console.log('点击编辑',copyEditRow)
    },
    cancelEdit() {
      this.editDialogVisible = false
    },
    saveEdit() {
      let self = this
      self.$refs["editForm"].validate((valid) => {
        if (valid) {
          //todo 调用接口存储
          request.post('/easyDisplay/saveData', {
            tableName: self.tableName,
            data: self.editForm,
          }, {
            headers: { 'Content-Type': 'application/json' }
          }).then(data => {
            self.$message.success('修改成功!');
            self.editDialogVisible = false
            //重置表单数据
            this.resetForm('editForm')
            //更新数据
            self.getData()
          }).catch(error => {
            console.error('新增数据失败:', error)
          })
        } else {
          return false;
        }
      });
    },
    handleSelectionChange(selectedRows) {
      this.selectedRows = selectedRows
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  }
}
</script>

<style lang="sass" scoped>
.easyDisplay {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  .header {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 20%;
    .operation {
      display: flex;
      flex-direction: row;
      width: 100%;
      height: 30%;
      justify-content: flex-start;
      align-items: center;
      .operationItem {
        margin: 0 20px 0 0;
      }
    }
    .query {
      display: flex;
      flex-direction: row;
      width: 100%;
      height: 70%;
      justify-content: flex-start;
      align-items: center;
    }
  }
  .table {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 70%;
    overflow: auto;
  }
  .footer {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: center;
    width: 100%;
    height: 10%;
  }
  .add_dialog_body {
    display: flex;
    flex-direction: column;
    padding: 0 10%;
  }
  .edit_dialog_body {
    display: flex;
    flex-direction: column;
    padding: 0 10%;
  }
}
</style>